<template>
  <el-form :model="form" ref="formRef" label-width="80px">
    <el-form-item
      label="发布日期"
      prop="date"
      :rules="[{ required: true, message: '请输入日期', trigger: 'blur' }]"
    >
      <el-date-picker
        v-model="form.date"
        type="date"
        placeholder="选择日期"
        value-format="YYYY-MM-DD"
        style="width: 100%"
      />
    </el-form-item>
    <el-form-item
      label="标题"
      prop="name"
      :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]"
    >
      <el-input v-model="form.name" placeholder="请输入公告标题" />
    </el-form-item>
    <el-form-item
      label="内容"
      prop="address"
      :rules="[{ required: true, message: '请输入内容', trigger: 'blur' }]"
    >
      <el-input
        type="textarea"
        v-model="form.address"
        placeholder="请输入公告内容"
        :rows="10"
      />
    </el-form-item>
  </el-form>
  <div class="btn">
    <el-button type="success" @click="submitForm">发布</el-button>
    <el-button type="info" @click="rewrite">重写</el-button>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import useNoticeStore from '@/store/modules/notice'

const NoticeStore = useNoticeStore()

interface Notice {
  id: string
  date: string
  name: string
  address: string
}

// 假设 tableData 在父组件中传入，或者你也可以在这里维护

const formRef = ref()
const form = reactive({
  date: '',
  name: '',
  address: '',
})

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return

    // 构造新公告对象
    const newNotice: Notice = {
      id: Date.now().toString(), // 简单生成唯一 id
      date: form.date,
      name: form.name,
      address: form.address,
    }

    // 添加到 tableData
    console.log(NoticeStore.addNotice)
    NoticeStore.addNotice(newNotice) // 新公告放在最前面
    ElMessage.success('发布成功')
    console.log(NoticeStore.tableData)

    // 重置表单
    form.date = ''
    form.name = ''
    form.address = ''
  })
}
const rewrite = () => {
  // 重置表单
  form.date = ''
  form.name = ''
  form.address = ''
}
</script>

<style scoped lang="scss">
.btn {
  text-align: center;
  .el-button {
    margin-top: 20px;
  }
}
.el-form {
  .el-form-item {
    margin-top: 20px;
  }
}
</style>
